//
//  SJAvatarBrowser.m
//  AnimationRecommend
//
//  Created by ljm on 2017/2/17.
//  Copyright © 2017年 ljm. All rights reserved.
//

#import "SJAvatarBrowser.h"
#import <Photos/Photos.h>
@interface SJAvatarBrowser()
@end


/*
 *     注意视图的层级关系：
 window层是视图的最底层，不具备弹窗的功能
 弹窗可以在window的view层上使用
 */

static CGRect oldframe;

@implementation SJAvatarBrowser

+(instancetype)share{
    static SJAvatarBrowser *share = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        share = [[SJAvatarBrowser alloc] init];
    });
    return share;
}


+ (void)showImage:(UIImageView *)avatarImageView{
    
    [SJAvatarBrowser share].saveImage = avatarImageView.image;
    
    UIImage *image = avatarImageView.image;
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    UIView *backgroundView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height)];
    oldframe = [avatarImageView convertRect:avatarImageView.bounds toView:window];
    backgroundView.backgroundColor = [UIColor blackColor];
    backgroundView.alpha = 0;
    UIImageView *imageView = [[UIImageView alloc]initWithFrame:oldframe];
    imageView.image = image;
    imageView.tag = 1;
    [backgroundView addSubview:imageView];
    [window.rootViewController.view addSubview:backgroundView];
    
    //点击隐藏---回到主页
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(hideImage:)];
    [backgroundView addGestureRecognizer: tap];
    
    //长按保存
    UILongPressGestureRecognizer *longTap = [[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(imglongTapClick:)];
    [backgroundView addGestureRecognizer:longTap];
    
    /*
     *    如果没有网络，不能加载图片；否则会崩溃
     */
    if (image == nil) {
        [MBProgressHUD py_showError:@"请等待图片加载完成" toView:nil];
        return;
    }
    [UIView animateWithDuration:0.3 animations:^{
        
        imageView.frame=CGRectMake(0,([UIScreen mainScreen].bounds.size.height-image.size.height*[UIScreen mainScreen].bounds.size.width/image.size.width)/2, [UIScreen mainScreen].bounds.size.width, image.size.height*[UIScreen mainScreen].bounds.size.width/image.size.width);
        backgroundView.alpha = 1;
        
    } completion:^(BOOL finished) {
        
    }];
}

#pragma mark -- 隐藏图片action
+(void)hideImage:(UITapGestureRecognizer*)tap{
    
    UIView *backgroundView=tap.view;
    UIImageView *imageView=(UIImageView*)[tap.view viewWithTag:1];
    
    [UIView animateWithDuration:0.3 animations:^{
        
        imageView.frame = oldframe;
        backgroundView.alpha = 0;
        
    } completion:^(BOOL finished) {
        
        [backgroundView removeFromSuperview];
        
    }];
}

#pragma mark -- 长按
+(void)imglongTapClick:(UILongPressGestureRecognizer *)gesture {
    
    if(gesture.state == UIGestureRecognizerStateBegan) {
        
      SRActionSheet *sr =  [SRActionSheet sr_actionSheetViewWithTitle:nil cancelTitle:@"取消" destructiveTitle:nil otherTitles:@[@"保存图片",@"分享图片"] otherImages:nil selectSheetBlock:^(SRActionSheet *actionSheet, NSInteger index) {
//          NSLog(@"%ld",index);
          switch (index) {
              case 0:
              //保存图片，保存到相册
  
              [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
  
                  //写入图片到相册
                  [PHAssetChangeRequest creationRequestForAssetFromImage:[SJAvatarBrowser share].saveImage];
  
              } completionHandler:^(BOOL success, NSError * _Nullable error) {
  
//                  NSLog(@"success = %d, error = %@", success, error);
                  if (!error) {
                      dispatch_queue_t queue = dispatch_get_main_queue();
                      dispatch_async(queue, ^{
                          [MBProgressHUD py_showSuccess:@"成功保存到相册" toView:nil];
                      });
                      
                  }else {
                     
                      dispatch_queue_t queue = dispatch_get_main_queue();
                      dispatch_async(queue, ^{
                          [MBProgressHUD py_showError:@"保存失败" toView:nil];
                      });

                  }
  
                 
                  
//              [[CLLScottAlertView alloc] showOnWindowWithTitle:@"确定" WithMessage:message];
              
//              UIAlertController *alertControl = [UIAlertController alertControllerWithTitle:@"提示" message:message preferredStyle:UIAlertControllerStyleAlert];
              

                  
//                  [[CLLMessageBarTool shareTool] showMessageWithType:TWMessageBarMessageTypeSuccess WithTitle:@"保存到相册" WithDescription:@"确定"];
                  
//              UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//                  //保存成功
//              }];
//              
//              [alertControl addAction:action];
              
//              [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:alertControl animated:YES completion:nil];
  
              }];
               
                  break;
                  
              default:
                  NSLog(@"选中了分享图片");
                  dispatch_queue_t queue = dispatch_get_main_queue();
                  dispatch_async(queue, ^{
                      [MBProgressHUD py_showSuccess:@"该功能暂时不能实现" toView:nil];
                  });
                  break;
          }
        }];
        
        [sr show];
        
//        UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
//        
//        [alertVC addAction:[UIAlertAction actionWithTitle:@"保存图片" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//            //保存图片，保存到相册
//
//            [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
//                
//                //写入图片到相册
//                PHAssetChangeRequest *req = [PHAssetChangeRequest creationRequestForAssetFromImage:[SJAvatarBrowser share].saveImage];
//                
//                
//            } completionHandler:^(BOOL success, NSError * _Nullable error) {
//                
//                NSLog(@"success = %d, error = %@", success, error);
//                
//               NSString*message =@"成功保存到相册";
//                
//                UIAlertController *alertControl = [UIAlertController alertControllerWithTitle:@"提示" message:message preferredStyle:UIAlertControllerStyleAlert];
//                
//                UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//                    //保存成功
//                }];
//                
//                [alertControl addAction:action];
//                
//                [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:alertControl animated:YES completion:nil];
//                
//            }];
// 
//        }]];
//        
//        [alertVC addAction:[UIAlertAction actionWithTitle:@"分享图片" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//            //分享图片
//            
//        }]];
//        
//        [alertVC addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
//            
//        }]];
//        
//        //推送弹窗
//        [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:alertVC animated:YES completion:^{
//            
//        }];
//    
    }
    
}

@end
